from web_ import constants, db
from web_.models import User, News, Category
from web_.utils.common import user_login_data
from web_.utils.image_storage import storage
from web_.utils.response_code import RET
from . import profile_blu
from flask import render_template, g, request, jsonify, current_app, abort



@profile_blu.route('/other_news_list')
def other_news_list():
    # 获取页数
    p = request.args.get("p", 1)
    user_id = request.args.get("user_id")
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    if not all([p, user_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    try:
        user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    if not user:
        return jsonify(errno=RET.NODATA, errmsg="用户不存在")

    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        # 获取当前页数据
        news_li = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    news_dict_li = []

    for news_item in news_li:
        news_dict_li.append(news_item.to_review_dict())
    data = {"news_list": news_dict_li, "total_page": total_page, "current_page": current_page}
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    """查看其他用户信息"""
    user = g.user

    # 获取其他用户id
    user_id = request.args.get("id")
    if not user_id:
        abort(404)
    # 查询用户模型
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)
    if not other:
        abort(404)

    # 判断当前登录用户是否关注过该用户
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == user.id).count() > 0:
            is_followed = True

    # 组织数据，并返回
    data = {
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template('news/other.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    '''
    我的关注
    :return:
    '''
    # 获取页数
    p = request.args.get("p", 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    user = g.user

    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followed.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        # 获取当前页数据
        follows = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    user_dict_li = []

    for follow_user in follows:
        user_dict_li.append(follow_user.to_dict())
    data = {
        "users": user_dict_li,
        "total_page": total_page,
        "current_page": current_page
    }
    return render_template('news/user_follow.html', data=data)



@profile_blu.route('/news_list')
@user_login_data
def news_list():
    '''
    个人新闻列表
    :return:
    '''
    page = request.args.get('p', 1)
    user = g.user
    try:
        page = int(page)
    except Exception as f:
        current_app.logger.error(f)
    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate_news = News.query.filter(News.user_id == user.id).paginate(page, constants.USER_COLLECTION_MAX_NEWS,False)
        news_li = paginate_news.items
        # 获取当前页
        current_page = paginate_news.page
        # 获取总页数
        total_page = paginate_news.pages
    except Exception as f:
        current_app.logger.error(f)
    news_lis = []
    for news in news_li:
        news_lis.append(news.to_review_dict())
    data = {
        'news_list':news_lis,
        'current_page ':current_page,
        'total_page':total_page
    }

    return render_template('news/user_news_list.html',data=data)


@profile_blu.route('/news_release', methods=['POST', 'GET'])
@user_login_data
def news_release():
    '''
    新闻发布
    :return:
    '''
    # 1.所有的新闻分类
    if request.method == 'GET':
        try:
            categorys = Category.query.all()
        except Exception as f:
            current_app.logger.error(f)
        # 2.将查到的所有分类加到列表中返回
        category_list = []
        for category in categorys:
            category_list.append(category.to_dict())
        # 3.删除第一个最新的分类
        category_list.pop(0)
        data = {
            'categories': category_list
        }
        return render_template('news/user_news_release.html', data=data)
    else:
        # 新闻标题
        title = request.form.get('title')
        # 新闻分类_id
        category_id = request.form.get('category_id')
        # 新闻摘要
        digest = request.form.get('digest')
        # 索引图片
        index_image = request.files.get('index_image')
        # 新闻内容
        content = request.form.get('content')
        source = '个人发布'

        # 2. 校验参数
        if not all([title, category_id, digest, index_image, content]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        try:
            index_image = index_image.read()
        except Exception as f:
            current_app.logger.error(f)
        try:
            category_id = int(category_id)
        except Exception as f:
            current_app.logger.error(f)
        try:
            key = storage(index_image)
        except Exception as f:
            current_app.logger.error(f)
            return jsonify(errno=RET.THIRDERR, errmsg="上传图片错误")
        new = News()
        new.title = title
        new.source = source
        new.category_id = category_id
        new.digest = digest
        new.content = content
        new.index_image_url = constants.QINIU_DOMIN_PREFIX + key
        new.user_id = g.user.id
        new.status = 1
        # 4. 保存到数据库

        try:
            db.session.add(new)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            db.session.rollback()
            return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
        return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route('/collection', methods=['POST', 'GET'])
@user_login_data
def new_collection():
    '''
    新闻收藏的展示
    :return:
    '''

    user = g.user
    page = request.args.get('p', 1)
    try:
        page = int(page)
    except Exception as f:
        current_app.logger.error(f)
    collections = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.collection_news.paginate(page, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页数据
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as f:
        current_app.logger.error(f)
    collection_list = []
    for collection in collections:
        collection_list.append(collection.to_basic_dict())

    data = {
        'total_page': total_page,
        'current_page': current_page,
        'collections': collection_list
    }
    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/pass_info', methods=['POST', 'GET'])
@user_login_data
def password_info():
    '''
    密码修改
    :return:
    '''
    user = g.user
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_pass_info.html', data=data)
    else:
        old_password = request.json.get('old_password')
        new_password = request.json.get('new_password')
        if not all(['GET', 'POST']):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        if not user.check_passowrd(old_password):
            return jsonify(errno=RET.DATAERR, errmsg="密码错误")
        user.password = new_password
        return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route('/pic_info', methods=['POST', 'GET'])
@user_login_data
def pic_info():
    '''
    改变头像
    :return:
    '''
    user = g.user
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_pic_info.html', data=data)
    else:
        # 1. 接收图像
        try:
            avatar = request.files.get('avatar').read()
        except Exception as f:
            current_app.logger.error(f)
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        # 2.上传图像
        try:
            key = storage(avatar)
        except Exception as f:
            current_app.logger.error(f)
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
        # 3.保存图像地址
        user.avatar_url = key
        # avatar_url = constants.QINIU_DOMIN_PREFIX + key
        return jsonify(errno=RET.OK, errmsg="OK", data={'avatar_url': constants.QINIU_DOMIN_PREFIX + key})


@profile_blu.route('/base_info', methods=['POST', 'GET'])
@user_login_data
def user_base():
    '''
    改变个人资料
    :return:
    '''
    user = g.user
    if request.method == 'GET':
        if user:
            data = {
                'user': user.to_dict()
            }
            return render_template('news/user_base_info.html', data=data)
    else:
        # 1. 接收参数
        nick_name = request.json.get('nick_name')
        signature = request.json.get('signature')
        gender = request.json.get('gender')
        # 2. 校验参数
        if not all([nick_name, signature, gender]):
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全吗")
        if gender not in ['MAN', 'WOMAN']:
            return jsonify(errno=RET.PARAMERR, errmsg="参数不全是吧")
        user.gender = gender
        user.nick_name = nick_name
        user.signature = signature

        return jsonify(errno=RET.OK, errmsg="OK")


@profile_blu.route('/info')
@user_login_data
def profile():
    user = g.user
    data = {
        'user': user.to_dict()
    }
    return render_template('news/user.html', data=data)
